package com.hengxinguotong.zhihuichengjian.ui.statistics.lift;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.LiftFormDataStatistics;
import com.hengxinguotong.zhihuichengjian.bean.LiftFormDataStatisticsRes;
import com.hengxinguotong.zhihuichengjian.ui.statistics.OnActivityInteractionListener;
import com.hengxinguotong.zhihuichengjian.utils.BarChartManager;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.LineChartManager;
import com.hengxinguotong.zhihuichengjian.utils.PieChartManager;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/3/28
 * <p>
 * 升降机报表-警报分析
 */

public class LiftFormDataWarningFragment extends BaseFragment implements OnActivityInteractionListener, OnChartValueSelectedListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.warning_state_pie_chart)
    PieChart warningStatePieChart;
    @BindView(R.id.equipment_warning_count_bar_chart)
    BarChart equipmentWarningCountBarChart;
    @BindView(R.id.warning_reason_situation_bar_chart)
    BarChart warningReasonSituationBarChart;
    @BindView(R.id.daily_warning_count_line_chart)
    LineChart dailyWarningCountLineChart;
    Unbinder unbinder;

    private BarChartManager equipmentCountBarChartManager,
            reasonSituationBarChartManager;
    private PieChartManager warningStatePieChartManager;
    private LineChartManager dailyCountLineChartManager;
    private String startTime,//开始时间
            endTime;//	结束时间（月报表时，为空）
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constants.FORMDATA_STATUS:
                    LiftFormDataStatistics liftStateFormData = (LiftFormDataStatistics) msg.obj;
                    if(liftStateFormData.getxData() == null || liftStateFormData.getxData().size() <= 0 ||
                            liftStateFormData.getyData() == null || liftStateFormData.getyData().size() <= 0 ){
                        warningStatePieChartManager.showNoDataText();
                    }else {
                        warningStatePieChartManager.setPieChart(getXData(liftStateFormData), getYData(liftStateFormData.getyData().get(0)), getColors3());
                    }
                    break;
                case Constants.FORMDATA_EQUIPMENT_COUNT:
                    LiftFormDataStatistics equipmentCountFormData = (LiftFormDataStatistics) msg.obj;
                    if(equipmentCountFormData.getxData() == null || equipmentCountFormData.getxData().size() <= 0 ||
                            equipmentCountFormData.getyData() == null || equipmentCountFormData.getyData().size() <= 0 ){
                        equipmentCountBarChartManager.showNoDataText();
                    }else {
                        equipmentCountBarChartManager.showBarChart(equipmentCountFormData.getxData(), getFData(equipmentCountFormData.getyData()),
                                new String[]{"预警", "报警"}, getColors2());
                    }
                    break;
                case Constants.FORMDATA_REASON:
                    LiftFormDataStatistics reasonFormData = (LiftFormDataStatistics) msg.obj;
                    if(reasonFormData.getxData() == null || reasonFormData.getxData().size() <= 0 ||
                            reasonFormData.getyData() == null || reasonFormData.getyData().size() <= 0 ){
                        reasonSituationBarChartManager.showNoDataText();
                    }else {
                        reasonSituationBarChartManager.showBarChart(reasonFormData.getxData(), getFData(reasonFormData.getyData()),
                                new String[]{"预警", "报警"}, getColors2());
                    }
                    break;
                case Constants.FORMDATA_DAILY_COUNT:
                    LiftFormDataStatistics dailyCountFormData = (LiftFormDataStatistics) msg.obj;
                    if(dailyCountFormData.getxData() == null || dailyCountFormData.getxData().size() <= 0 ||
                            dailyCountFormData.getyData() == null || dailyCountFormData.getyData().size() <= 0 ){
                        dailyCountLineChartManager.showNoDataText();
                    }else {
                        dailyCountLineChartManager.showLineChart(dailyCountFormData.getxData(), dailyCountFormData.getyData().get(0), "预警", getResources().getColor(R.color.color_FD9D00));
                        dailyCountLineChartManager.addLine(dailyCountFormData.getyData().get(1), "报警", getResources().getColor(R.color.color_F5573F));
                    }
                    break;
            }
        }
    };

    public LiftFormDataWarningFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param startTime Parameter .
     * @param endTime   Parameter .
     * @return A new instance of fragment LiftDataStatisticsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static LiftFormDataWarningFragment newInstance(String startTime, String endTime) {
        LiftFormDataWarningFragment fragment = new LiftFormDataWarningFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, startTime);
        args.putString(ARG_PARAM2, endTime);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            startTime = getArguments().getString(ARG_PARAM1);
            endTime = getArguments().getString(ARG_PARAM2);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_lift_form_data_warning, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        warningStatePieChartManager = new PieChartManager(warningStatePieChart);
        warningStatePieChartManager.setLegend();
        equipmentCountBarChartManager = new BarChartManager(equipmentWarningCountBarChart);
        equipmentCountBarChartManager.setLegend();
        reasonSituationBarChartManager = new BarChartManager(warningReasonSituationBarChart);
        reasonSituationBarChartManager.setLegend();
        dailyCountLineChartManager = new LineChartManager(dailyWarningCountLineChart);
        dailyCountLineChartManager.setLegend();
    }

    @Override
    public void onLazyLoad() {
        initData();
    }

    private void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getStatusChartData("搜索中…");
                getEquipmentChartData("搜索中…");
                getReasonChartData("搜索中…");
                getDailyCountChartData("搜索中…");
            }
        }, 500);
    }

    /**
     * 警报状态
     * @param alert
     */
    public void getStatusChartData(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(getActivity(), "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/lifterReport/countWarningAndAlarmAndNormal/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    LiftFormDataStatisticsRes res = gson.fromJson(json, LiftFormDataStatisticsRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_STATUS;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    /**
     * 各设备警报次数
     * @param alert
     */
    public void getEquipmentChartData(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(getActivity(), "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/lifterReport/countWarningAndAlarmGroupByEquipmentName/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    LiftFormDataStatisticsRes res = gson.fromJson(json, LiftFormDataStatisticsRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_EQUIPMENT_COUNT;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    /**
     * 警报原因分布情况
     * @param alert
     */
    public void getReasonChartData(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(getActivity(), "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/lifterReport/countWarningAndAlarmGroupByCause/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    LiftFormDataStatisticsRes res = gson.fromJson(json, LiftFormDataStatisticsRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_REASON;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    /**
     * 每天警报次数
     * @param alert
     */
    public void getDailyCountChartData(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(getActivity(), "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/lifterReport/countWarningAndAlarmGroupByDays/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    LiftFormDataStatisticsRes res = gson.fromJson(json, LiftFormDataStatisticsRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_DAILY_COUNT;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    @Override
    public void OnActivityInteraction(String startTime, String endTime) {
        this.startTime = startTime;
        this.endTime = endTime;
        initData();
    }

    private List<Integer> getColors2() {
        List<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.color_F5573F));
        colors.add(getResources().getColor(R.color.color_FD9D00));
        return colors;
    }

    private List<Integer> getColors3(){
        List<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.color_EEEEEE));
        colors.add(getResources().getColor(R.color.color_FD9D00));
        colors.add(getResources().getColor(R.color.color_F5573F));
        return colors;
    }

    private List<String> getXData(LiftFormDataStatistics data){
        List<String> xData = new ArrayList<>();
        for (int i = 0; i < data.getxData().size(); i++) {
            String x = data.getxData().get(i) + " " + data.getyData().get(1).get(i) + " " + data.getyData().get(0).get(i) + "次";
            xData.add(x);
        }
        return xData;
    }

    private List<Float> getYData(List<String> data){
        List<Float> yData = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            float y = Float.parseFloat(data.get(i));
            yData.add(y);
        }
        return yData;
    }

    private List<List<Float>> getFData(List<List<String>> data) {
        List<List<Float>> yData = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            List<Float> mData = new ArrayList<>();
            for (int j = 0; j < data.get(i).size(); j++) {
                mData.add(Float.parseFloat(data.get(i).get(j)));
            }
            yData.add(mData);
        }
        return yData;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        if (e == null)
            return;
        Log.i("VAL SELECTED",
                "Value: " + e.getY() + ", index: " + h.getX()
                        + ", DataSet index: " + h.getDataSetIndex());
    }

    @Override
    public void onNothingSelected() {
        Log.i("PieChart", "nothing selected");
    }
}
